package com.authentication.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 用于实现 resource server 认证的 过滤器
 */
public class ResourceServerAuthenticationFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String authorization = request.getHeader("Authorization");

        if (authorization == null) {
            return;
        }

        String[] basicAndToken = authorization.split("Basic ");

        byte[] decode = Base64.getDecoder().decode(basicAndToken[1]);

        String[] userNamePassword = new String(decode, StandardCharsets.UTF_8).split(":");

        //TODO 从仓库中根据用户名和密码来验证 resource server 的有效性

        if (userNamePassword.length == 2 && "user_resource_server".equals(userNamePassword[0]) && "user_resource_server_password".equals(userNamePassword[1])) {
            TestingAuthenticationToken authentication = new TestingAuthenticationToken(userNamePassword[0], "");

            authentication.setAuthenticated(true);

            SecurityContextHolder.getContext().setAuthentication(
                    authentication
            );
            filterChain.doFilter(request, response);
        }

    }

}
